import java.awt.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.*;

/**
 * Created by lanouhn on 17/7/18.
 */
public class JavaImageRequest {

    public static void  main(String[] args){

        HttpURLConnection connection = null;
        InputStream is ;//输入流，接收网络请求结果

        try {
            String myUrl = "https://cn.bing.com/az/hprichbg/rb/GeladaSimien_ZH-CN8344110980_1920x1080.jpg";
            URL url = new URL(myUrl);
//            通过网址打开网络连接
            connection  =(HttpURLConnection)url.openConnection();

//            判断网络响应
            int code  = connection.getResponseCode();
            if(code == 200){
                System.out.print("1111");
                is = connection.getInputStream();
                byte[] data = new byte[1024];
                int len ;
//                存取结果
                File file = new File( "/Users/lanouhn/Desktop/");
                OutputStream outputStream = new FileOutputStream(file.getPath()+"/"+"12.jpg");
                while ((len = is.read(data))!= -1){
                    outputStream.write(data,0,len);
                }
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
//            网络请求结束，及时的关流，断网，防止流量浪费
//            防止网络长期保持连接不安全
            if (connection != null) {
                connection.disconnect();
            }
        }
//       
    }
}
